<template>
  <div class="singer">
    <list-view :data="singerLists" @selected="selectedItem"></list-view>
    <router-view></router-view>
  </div>
</template>

<script>
import Singer from 'util/singer'
import ListView from '../../base/listView/listView'
import { ERR_OK } from '../../apis/config.js'
import { getSingerList } from 'api/singers.js'
import { mapMutations } from 'vuex'
const HotName = '热门'
const HotSingerLen = 10
export default {
  data() {
    return {
      singers: [],
      singerLists: []
    }
  },
  components: {
    ListView
  },
  created() {
    getSingerList().then(res => {
      console.log(res)
      if (res.code === ERR_OK) {
        this.singers = res.data.list
        this._dealSingers(this.singers)
      }
    })
  },

  methods: {
    // 点击item
    selectedItem(item) {
      this.$router.push({ path: `/singer/:${item.id}` })
      this.setSinger(item) // 相当于 this.$store.commit('SET_SINGER')
    },
    // 处理singers 进行a-z分组
    _dealSingers(list) {
      let singerList = {
        hot: {
          title: HotName,
          item: []
        }
      }
      list.forEach((item, index) => {
        if (index < HotSingerLen) {
          //选出热门
          singerList.hot.item.push(
            new Singer({
              id: item.Fsinger_mid,
              name: item.Fsinger_name
            })
          )
        }
        // 创建A-Z序号,进行分组
        const key = item.Findex
        if (!singerList[key]) {
          singerList[key] = {
            title: key,
            item: []
          }
        }
        singerList[key].item.push(
          new Singer({
            id: item.Fsinger_mid,
            name: item.Fsinger_name
          })
        )
      })
      this.singerLists = this._sortSingers(singerList)
      console.log(this.singerLists)
    },
    // 对分组进行排序
    _sortSingers(list) {
      let hot = [] //存放hot数据
      let rest = [] // 存放A-Z数据
      for (let key in list) {
        let value = list[key]
        if (value.title.match(/[a-zA-Z]/)) {
          rest.push(value)
        } else if (value.title === HotName) {
          hot.push(value)
        }
      }
      rest.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(rest)
    },
    // 方法映射
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  }
}
</script>

<style scoped lang="stylus">
.singer {
  position: fixed;
  width: 100%;
  top: 88px;
  bottom: 0;
}
</style>